//preloading.....
load("library/common.js");

JEuler.system.loadJS("library/math.js");

(function() {
    
    JEuler.system.printCaption("61");
    JEuler.system.startTimerCount();
    
    function getAll4Digital(f) {
        var result = [], n=1, value;
        do{
            n++; 
            value = f(n);
            if(value> 9999) return result;
            if(value>=1000) result.push(value);
        }while(1);
    };
    
    function test(a,b) {
        var t1=(a%100); if(t1<10) return false;
        var t2=(b%100); if(t2<10) return false;
        var t3= Math.floor(b/100);
        return t1==t3;
    }
    
    var triangles   = getAll4Digital(function(n) {return n*(n+1)/2;});
    var squares     = getAll4Digital(function(n) {return n*n;});
    var pentagonals = getAll4Digital(function(n) {return n*(3*n-1)/2;});
    var hexagonals  = getAll4Digital(function(n) {return n*(2*n-1);});
    var heptagonals = getAll4Digital(function(n) {return n*(5*n-3)/2;});
    var octagonals  = getAll4Digital(function(n) {return n*(3*n-2);});
    
    var sets0 = [triangles, squares, pentagonals, hexagonals, heptagonals, octagonals];
    var sets = sets0;
    
    var permutation = new JEuler.math.Permutation("012345");

    var findNumbers = [], findIndex = [], iSetIndex=0, a=0, b=0, i=0, order;
    do {
        if(iSetIndex == -1) {
            order = permutation.next();
            if(order) {
                order = order.split("");
                sets = [];
                for(var i=0; i<6; i++) {
                    sets[i] = sets0[order[i]];
                }
                iSetIndex = 0; 
                i=0;
            } else {
                JEuler.system.print("Not Find .... ERROR")
                break;
            }
        }
    
        if(i>=sets[iSetIndex].length) {
            iSetIndex--;
            findNumbers.pop();
            i = findIndex.pop() + 1;
            //print(findNumbers);
            continue;
        }
    
        a = findNumbers[findNumbers.length-1] || -1;
        b = sets[iSetIndex][i];
        if(a==-1 || test(a,b)) {
            if(findNumbers.length==5) {
                if(test(b, findNumbers[0])) {
                    findNumbers.push(b);
                    JEuler.system.print("\nFIND....");
                    JEuler.system.print(findNumbers);
                    JEuler.system.print("SUM=" + eval(findNumbers.join("+")));
                    break;
                } else {
                    i++;
                }
            } else {
                findNumbers.push(b);
                findIndex.push(i);
                //print(findNumbers);
                iSetIndex++;
                i=0;
            }
        } else {
            i++;
        }
        
    } while(1);
    
    JEuler.system.printTimerCount();
    
})();
